package cn.learn.athena.controller;

import cn.learn.athena.exception.AthenaRuntimeException;
import cn.learn.athena.exception.ValidateException;
import cn.learn.athena.model.User;
import cn.learn.athena.service.IUserService;
import cn.learn.athena.util.Result;
import cn.learn.athena.util.Validation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zlj
 * @Date 2018/10/29
 * @des
 */

@RestController
@RequestMapping("/")
public class UserController {
    
    @Autowired
    private IUserService userService;
    
    @RequestMapping(value="/login")
    public User login(String loginName, String password) {
        User qUser = userService.findUserByLoginNameAndPassword(loginName, password);
        return qUser ;
    }

    /**
    * 功能:
    * fetch 接口不需要写怎么详细 功能多了
    * @param
    * @return  
    * @date 2019/1/4
    */
    @RequestMapping( value = "/addUser" , method = RequestMethod.POST)
    public Result addUser(@RequestBody  User user) {
        Validation.isTrue(StringUtils.isNotBlank(user.getLoginName()) &&
                StringUtils.isNotBlank(user.getPassword()),"用户名和密码不能为空!");
        User user1 = userService.findUserByLoginName(user.getLoginName());
        if (user1 != null) {
            throw new AthenaRuntimeException("用户名已存在!");
        }
        Result result = new Result();
        int i = userService.addUser(user);
        if(i == 0) {
           result.setErr("添加用户失败");
        }
        return result ;
    }

    @RequestMapping(value = "/findUserByName" , method = RequestMethod.GET)
    public User findUserByName(String userName) {
        return userService.findUserByLoginName(userName);
    }
}
